//
//  UserViewController.m
//  MyVirtualDiary
//
//  Created by Alexander Wallis on 10.07.13.
//  Copyright (c) 2013 Alexander Wallis. All rights reserved.
//

#import "UserViewController.h"
#import "AddEntryViewController.h"
#import "EntryViewController.h"

@interface UserViewController ()

@end

@implementation UserViewController {
    NSArray *searchResults;
}

@synthesize entryArray;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    [self loadTableData];
}

-(IBAction)logout:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //self.navigationController.navigationBar.topItem.title = self.userID;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods
-(AppDelegate *)appDelegate{

    return (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"AddEntry"]) {
        AddEntryViewController *destinationViewController = segue.destinationViewController;
        destinationViewController.userID = self.userID; 
    }
}

-(void)loadTableData{

    NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:context];
    
    [fetchRequest setEntity:entity];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"user==%@", self.userID];
    [fetchRequest setPredicate:predicate];
    
    NSError *error = nil;
    self.entryArray = [context executeFetchRequest:fetchRequest error:&error];
    [self.tableView reloadData];
}

-(void) filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
    searchResults = [entryArray filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];
    }else{
        return [entryArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    Entry *entry = [self.entryArray objectAtIndex:indexPath.row];
    
    cell.textLabel.text = entry.titel;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-DD"];
    NSString *theDate = [dateFormatter stringFromDate:entry.date];
    cell.detailTextLabel.text= theDate;
    
    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete object from database
        Entry *entry = [self.entryArray objectAtIndex:indexPath.row];
        [context deleteObject:[context objectWithID:[entry objectID]]];
        
        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"can't delete entry: %@", [error userInfo]);
            return;
        }
        
        // Remove entry from table view
        NSMutableArray *array = [self.entryArray mutableCopy];
        [array removeObjectAtIndex:indexPath.row];
        self.entryArray = array;
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    EntryViewController *entryViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"EntryViewController"];
    
    Entry * entry = [self.entryArray objectAtIndex:indexPath.row];
    entryViewController.entryID = [entry objectID];
    
    [self.navigationController pushViewController:entryViewController animated:YES];
}

@end
